<template>
  <div>
    <el-upload
      ref="uploadDomestic"
      :action="uploadUrl"
      list-type="picture-card"
      :on-success="handleImgSuccess"
      :before-upload="handleBeforeupload"
      :on-preview="handleImgPreview"
      :on-exceed="handleExceed"
      :on-error="handError"
      :data="filesData"
      :on-remove="handImgRemove"
      multiple
      :disabled="disabled"
      :limit="limit"
      :file-list="fileList"
      :class="objClass"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <div>
      <el-dialog :visible.sync="dialogVisible" append-to-body>
        <img width="100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { BASE_URL } from '@/utils/environment'
export default {
  props: {
    value: {
      type: [String, Array],
      default: ''
    },
    widths: {
      type: Number,
      default: null
    },
    heights: {
      type: Number,
      default: null
    },
    // 文件大小限制  单位：兆
    sizeLimit: {
      type: Number,
      default: 5
    },
    // 文件数量限制 默认1
    limit: {
      type: Number,
      default: 1
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      uploadUrl: `${BASE_URL}/upload`,
      objClass: { upLoadShow: true, upLoadHide: false },

      filesData: {
        files: null
      },
      // 查看大图路径
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  computed: {
    imgFile: {
      get() {
        return this.value
      },
      set(value) {
        this.$emit('input', value)
      }
    },
    widthVal() {
      return this.widths + 'px'
    },
    heightVal() {
      return this.heights + 'px'
    }
  },
  watch: {
    fileList(value) {
      if (value) {
        console.log(value, '文件更新')
        this.imgFile = value.map(el => el.url)
        this.updateUpLoadIcon()
      }
    },
    imgFile: {
      handler(value) {
        if (value) {
          if (typeof value === 'string') {
            const list = value.split(',')
            this.fileList = list.map(el => ({
              url: el,
              name: el
            }))
          }
        }
      },
      immediate: true
    }
  },

  methods: {
    /**
     * @description 上传图片相关
     * @handleImgSuccess 上传成功
     * @handImgRemove 删除图片
     * @handleBeforeupload 上传前校验
     * @handleExceed 超出最大上传限额
     *
     */
    handleImgSuccess(res, file) {
      console.log(res, file)
      const obj = {
        name: file.name,
        url: file.response[0]
      }
      this.fileList.push(obj)
    },
    handImgRemove(res) {
      console.log(res)
      this.fileList = this.fileList.filter(el => el.uid != res.uid)
    },
    handleBeforeupload(file) {
      this.filesData.files = file
      const isJPG = 'image/jpeg,image/png,image/jpg'.indexOf(file.type) != -1
      const isLt2M = file.size / 1024 / 1024 < this.sizeLimit
      if (!isJPG) {
        this.$message.error('图片只能是 jpg,png,jpeg 格式!')
        this.allLoding = false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 ' + this.sizeLimit + 'MB!')
        this.allLoding = false
      }
      return isJPG && isLt2M
    },
    handleExceed() {
      this.$message({
        message: `超出最大上传数量,最多可上传${this.limit}张图片`,
        type: 'error'
      })
    },

    // 超出数量限制隐藏上传按钮
    updateUpLoadIcon() {
      const { fileList } = this

      // 超出；隐藏上传按钮
      if (fileList.length >= parseInt(this.limit)) {
        this.objClass.upLoadHide = true
      } else {
        this.objClass.upLoadHide = false
      }
      this.objClass.upLoadShow = !this.objClass.upLoadHide
    },

    // 查看大图
    handleImgPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handError(err) {
      console.log('上传失败', err)
      this.$message.error('上传失败')
    }
  }
}
</script>

<style lang="scss" scoped>
.singleImage {
  .el-upload.el-upload--text {
    text-align: left;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 100%;
    line-height: 100%;
    text-align: center;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
  }
  .avatar {
    // width: 100%;
    // height: 100%;
    display: block;
  }

  .image-preview {
    width: 100%;
    height: 100%;
    position: relative;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    float: left;
    border-radius: 6px;
  }
}

/*当upLoadHide为true时，启用如下样式，即上传框的样式，若为false则不启用该样式*/
.upLoadHide {
  position: relative;
  /deep/ .el-upload-list__item {
    transition: none !important;
  }
  /deep/ .el-upload {
    display: none !important;
  }
}

.upLoadShow {
  position: relative;
  /deep/ .el-upload-list__item {
    transition: none !important;
  }
  /deep/ .el-upload {
    z-index: 1000;
  }
}

.el-dialog__wrapper /deep/ .el-dialog {
  margin-top: 0px !important;
}
</style>
